# -*- coding: utf-8 -*-
from django import forms

from google.appengine.ext.db import djangoforms
from base.models import ETeacher, TimeSlot
from base.util.decorators import render_to, login_required
import logging


@login_required
@render_to('timeslot/list.html')
def list(request, eteacher_id):
    eteacher = ETeacher.get_using_id(int(eteacher_id))
    timeslots = db.get(eteacher.not_available_times)
    return {'timeslots': timeslots}

class TimeSlotForm(djangoforms.ModelForm):
    class Meta:
        model = TimeSlot
        exclude = ('id',)

#    def clean(self):
#        pass
#        cleaned_data = self.cleaned_data
#        name = cleaned_data.get('name')
#        if School.is_existed(name):
#            raise forms.ValidationError(u'You already have the same school\'s name')
#        return cleaned_data

@login_required
@render_to('timeslot/form.html')
def create(request, eteacher_id):
    form = TimeSlotForm()
    if request.method == 'POST':
        form = TimeSlotForm(request.POST)
        if form.is_valid():
            timeslot = form.save(commit=False)
            timeslot.put()
            eteacher = ETeacher.get_using_id(int(eteacher_id))
            eteacher.not_available_times.append(timeslot.key())
            eteacher.put()
            return eteacher.get_absolute_url
    return {'form': form}

@login_required
@render_to('timeslot/detail.html')
def detail(request, timeslot_id):
    timeslot = TimeSlot.get_using_id(int(timeslot_id))
    return {'timeslot': timeslot}

@login_required
@render_to('timeslot/form.html')
def change(request, timeslot_id):
    timeslot = TimeSlot.get_using_id(int(timeslot_id))
    form = TimeSlotForm(request.POST or None, instance=timeslot)
    if form.is_valid():
        timeslot = form.save()
        return timeslot.get_absolute_url
    return {'form': form}